{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: openai in d:\\java\\miniconda3\\envs\\langchain\\lib\\site-packages (1.77.0)\n",
      "Requirement already satisfied: anyio<5,>=3.5.0 in d:\\java\\miniconda3\\envs\\langchain\\lib\\site-packages (from openai) (4.6.2)\n",
      "Requirement already satisfied: distro<2,>=1.7.0 in d:\\java\\miniconda3\\envs\\langchain\\lib\\site-packages (from openai) (1.9.0)\n",
      "Requirement already satisfied: httpx<1,>=0.23.0 in d:\\java\\miniconda3\\envs\\langchain\\lib\\site-packages (from openai) (0.27.0)\n",
      "Requirement already satisfied: jiter<1,>=0.4.0 in d:\\java\\miniconda3\\envs\\langchain\\lib\\site-packages (from openai) (0.9.0)\n",
      "Requirement already satisfied: pydantic<3,>=1.9.0 in d:\\java\\miniconda3\\envs\\langchain\\lib\\site-packages (from openai) (2.9.2)\n",
      "Requirement already satisfied: sniffio in d:\\java\\miniconda3\\envs\\langchain\\lib\\site-packages (from openai) (1.3.0)\n",
      "Requirement already satisfied: tqdm>4 in d:\\java\\miniconda3\\envs\\langchain\\lib\\site-packages (from openai) (4.67.1)\n",
      "Requirement already satisfied: typing-extensions<5,>=4.11 in d:\\java\\miniconda3\\envs\\langchain\\lib\\site-packages (from openai) (4.12.2)\n",
      "Requirement already satisfied: idna>=2.8 in d:\\java\\miniconda3\\envs\\langchain\\lib\\site-packages (from anyio<5,>=3.5.0->openai) (3.7)\n",
      "Requirement already satisfied: certifi in d:\\java\\miniconda3\\envs\\langchain\\lib\\site-packages (from httpx<1,>=0.23.0->openai) (2025.1.31)\n",
      "Requirement already satisfied: httpcore==1.* in d:\\java\\miniconda3\\envs\\langchain\\lib\\site-packages (from httpx<1,>=0.23.0->openai) (1.0.2)\n",
      "Requirement already satisfied: h11<0.15,>=0.13 in d:\\java\\miniconda3\\envs\\langchain\\lib\\site-packages (from httpcore==1.*->httpx<1,>=0.23.0->openai) (0.14.0)\n",
      "Requirement already satisfied: annotated-types>=0.6.0 in d:\\java\\miniconda3\\envs\\langchain\\lib\\site-packages (from pydantic<3,>=1.9.0->openai) (0.7.0)\n",
      "Requirement already satisfied: pydantic-core==2.23.4 in d:\\java\\miniconda3\\envs\\langchain\\lib\\site-packages (from pydantic<3,>=1.9.0->openai) (2.23.4)\n",
      "Requirement already satisfied: colorama in d:\\java\\miniconda3\\envs\\langchain\\lib\\site-packages (from tqdm>4->openai) (0.4.6)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000021D4AF23810>: Failed to establish a new connection: [WinError 10061] 由于目标计算机积极拒绝，无法连接。'))': /simple/openai/\n",
      "WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000021D4AF24AD0>: Failed to establish a new connection: [WinError 10061] 由于目标计算机积极拒绝，无法连接。'))': /simple/openai/\n",
      "WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000021D4AF25350>: Failed to establish a new connection: [WinError 10061] 由于目标计算机积极拒绝，无法连接。'))': /simple/openai/\n",
      "WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000021D4AF25C10>: Failed to establish a new connection: [WinError 10061] 由于目标计算机积极拒绝，无法连接。'))': /simple/openai/\n",
      "WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000021D4AF26490>: Failed to establish a new connection: [WinError 10061] 由于目标计算机积极拒绝，无法连接。'))': /simple/openai/\n"
     ]
    }
   ],
   "source": [
    "!pip install --upgrade openai"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "outputs": [],
   "source": [
    "import os\n",
    "from openai import OpenAI\n",
    "\n",
    "# 国内代理方式\n",
    "client = OpenAI(\n",
    "    api_key = \"sk-y7DHfp9fzuCxOVm2158638099f9541D3833aB4F4Ed674aCf\",\n",
    "    base_url = \"https://vip.apiyi.com/v1\"    # 此处代理方式，如果是OpenAI官方接口需调整接口地址\n",
    ")"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "outputs": [],
   "source": [
    "prompt = \"\"\"请帮我用 HTML 生成一个五子棋游戏，所有代码都保存在一个 HTML 中。不需要包含前后缀的文字说明，直接生成完整的、可运行的纯html，我将对结果保存至文件直接运行\"\"\""
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "outputs": [],
   "source": [
    "try:\n",
    "    # 调用 DeepSeek Chat API\n",
    "    response = client.chat.completions.create(\n",
    "        model=\"deepseek-chat\",  # 或 DeepSeek 提供的其他模型名称\n",
    "        messages=[\n",
    "            {\"role\": \"system\", \"content\": \"你是一个专业的 Web 开发助手，擅长用 HTML/CSS/JavaScript 编写游戏。\"},\n",
    "            {\"role\": \"user\", \"content\": prompt}\n",
    "        ],\n",
    "        temperature=0.7,\n",
    "        stream=False\n",
    "    )\n",
    "\n",
    "\n",
    "except Exception as e:\n",
    "    print(f\"调用 API 出错: {e}\")"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "outputs": [
    {
     "data": {
      "text/plain": "'```html\\n<!DOCTYPE html>\\n<html>\\n<head>\\n    <meta charset=\"UTF-8\">\\n    <title>五子棋</title>\\n    <style>\\n        body {\\n            display: flex;\\n            justify-content: center;\\n            align-items: center;\\n            flex-direction: column;\\n            font-family: Arial, sans-serif;\\n            background-color: #f5f5dc;\\n        }\\n        h1 {\\n            color: #8b4513;\\n        }\\n        #game-container {\\n            position: relative;\\n            margin: 20px;\\n        }\\n        #board {\\n            background-color: #deb887;\\n            display: grid;\\n            grid-template-columns: repeat(15, 40px);\\n            grid-template-rows: repeat(15, 40px);\\n            border: 2px solid #8b4513;\\n            box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);\\n        }\\n        .cell {\\n            width: 40px;\\n            height: 40px;\\n            box-sizing: border-box;\\n            position: relative;\\n            cursor: pointer;\\n        }\\n        .cell::before, .cell::after {\\n            content: \\'\\';\\n            position: absolute;\\n            background-color: #000;\\n        }\\n        .cell::before {\\n            width: 100%;\\n            height: 1px;\\n            top: 50%;\\n            left: 0;\\n        }\\n        .cell::after {\\n            width: 1px;\\n            height: 100%;\\n            left: 50%;\\n            top: 0;\\n        }\\n        .black, .white {\\n            position: absolute;\\n            width: 32px;\\n            height: 32px;\\n            border-radius: 50%;\\n            top: 4px;\\n            left: 4px;\\n            z-index: 1;\\n        }\\n        .black {\\n            background-color: #000;\\n            box-shadow: 0 0 5px rgba(0, 0, 0, 0.7);\\n        }\\n        .white {\\n            background-color: #fff;\\n            box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);\\n        }\\n        #status {\\n            margin-top: 20px;\\n            font-size: 24px;\\n            color: #8b4513;\\n        }\\n        #restart {\\n            margin-top: 20px;\\n            padding: 10px 20px;\\n            font-size: 16px;\\n            background-color: #8b4513;\\n            color: white;\\n            border: none;\\n            border-radius: 5px;\\n            cursor: pointer;\\n        }\\n        #restart:hover {\\n            background-color: #a0522d;\\n        }\\n    </style>\\n</head>\\n<body>\\n    <h1>五子棋</h1>\\n    <div id=\"game-container\">\\n        <div id=\"board\"></div>\\n    </div>\\n    <div id=\"status\">黑方回合</div>\\n    <button id=\"restart\">重新开始</button>\\n\\n    <script>\\n        document.addEventListener(\\'DOMContentLoaded\\', () => {\\n            const board = document.getElementById(\\'board\\');\\n            const statusDisplay = document.getElementById(\\'status\\');\\n            const restartButton = document.getElementById(\\'restart\\');\\n            \\n            let currentPlayer = \\'black\\';\\n            let gameState = Array(15).fill().map(() => Array(15).fill(null));\\n            let gameActive = true;\\n            \\n            // 创建棋盘\\n            function createBoard() {\\n                board.innerHTML = \\'\\';\\n                for (let i = 0; i < 15; i++) {\\n                    for (let j = 0; j < 15; j++) {\\n                        const cell = document.createElement(\\'div\\');\\n                        cell.classList.add(\\'cell\\');\\n                        cell.dataset.row = i;\\n                        cell.dataset.col = j;\\n                        cell.addEventListener(\\'click\\', handleCellClick);\\n                        board.appendChild(cell);\\n                    }\\n                }\\n            }\\n            \\n            // 处理点击事件\\n            function handleCellClick(e) {\\n                if (!gameActive) return;\\n                \\n                const row = parseInt(e.target.dataset.row);\\n                const col = parseInt(e.target.dataset.col);\\n                \\n                if (gameState[row][col] !== null) return;\\n                \\n                gameState[row][col] = currentPlayer;\\n                renderPiece(row, col, currentPlayer);\\n                \\n                if (checkWin(row, col)) {\\n                    statusDisplay.textContent = `${currentPlayer === \\'black\\' ? \\'黑方\\' : \\'白方\\'}获胜!`;\\n                    gameActive = false;\\n                    return;\\n                }\\n                \\n                currentPlayer = currentPlayer === \\'black\\' ? \\'white\\' : \\'black\\';\\n                statusDisplay.textContent = `${currentPlayer === \\'black\\' ? \\'黑方\\' : \\'白方\\'}回合`;\\n            }\\n            \\n            // 渲染棋子\\n            function renderPiece(row, col, player) {\\n                const cell = document.querySelector(`[data-row=\"${row}\"][data-col=\"${col}\"]`);\\n                const piece = document.createElement(\\'div\\');\\n                piece.classList.add(player);\\n                cell.appendChild(piece);\\n            }\\n            \\n            // 检查胜利条件\\n            function checkWin(row, col) {\\n                const directions = [\\n                    [0, 1],   // 水平\\n                    [1, 0],   // 垂直\\n                    [1, 1],   // 对角线\\n                    [1, -1]   // 反对角线\\n                ];\\n                \\n                for (const [dx, dy] of directions) {\\n                    let count = 1;\\n                    \\n                    // 正向检查\\n                    for (let i = 1; i < 5; i++) {\\n                        const newRow = row + i * dx;\\n                        const newCol = col + i * dy;\\n                        if (newRow < 0 || newRow >= 15 || newCol < 0 || newCol >= 15 || \\n                            gameState[newRow][newCol] !== currentPlayer) {\\n                            break;\\n                        }\\n                        count++;\\n                    }\\n                    \\n                    // 反向检查\\n                    for (let i = 1; i < 5; i++) {\\n                        const newRow = row - i * dx;\\n                        const newCol = col - i * dy;\\n                        if (newRow < 0 || newRow >= 15 || newCol < 0 || newCol >= 15 || \\n                            gameState[newRow][newCol] !== currentPlayer) {\\n                            break;\\n                        }\\n                        count++;\\n                    }\\n                    \\n                    if (count >= 5) return true;\\n                }\\n                \\n                return false;\\n            }\\n            \\n            // 重新开始游戏\\n            function restartGame() {\\n                gameState = Array(15).fill().map(() => Array(15).fill(null));\\n                currentPlayer = \\'black\\';\\n                gameActive = true;\\n                statusDisplay.textContent = \\'黑方回合\\';\\n                createBoard();\\n            }\\n            \\n            restartButton.addEventListener(\\'click\\', restartGame);\\n            \\n            // 初始化游戏\\n            createBoard();\\n        });\\n    </script>\\n</body>\\n</html>\\n```'"
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response.choices[0].message.content"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "五子棋游戏已保存为 gomoku.html\n"
     ]
    }
   ],
   "source": [
    "    if response.choices and len(response.choices) > 0:\n",
    "        html_content = response.choices[0].message.content\n",
    "\n",
    "        # 保存到文件\n",
    "        with open(\"gomoku.html\", \"w\", encoding=\"utf-8\") as f:\n",
    "            f.write(html_content)\n",
    "        print(\"五子棋游戏已保存为 gomoku.html\")\n",
    "    else:\n",
    "        print(\"未收到有效响应\")"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}